package com.leorui.schoollife.utils

import java.io.File
import java.io.FileInputStream
import java.security.MessageDigest

class EncryptUtils {

    fun convert2SHA256(value: String): String {
        val digest = MessageDigest.getInstance("SHA-256")
        val convertByteArray: ByteArray = digest.digest(value.toByteArray())
        return toHex(convertByteArray)
    }

    fun convert2MD5(value: String): String {
        val digest = MessageDigest.getInstance("MD5")
        val convertByteArray: ByteArray = digest.digest(value.toByteArray())
        return toHex(convertByteArray)
    }

    fun convert2MD5(value: File): String {
        val digest = MessageDigest.getInstance("MD5")

        val inputStream = FileInputStream(value)
        val buffer = ByteArray(1024)
        var len = 0
        len = inputStream.read(buffer, 0, buffer.size)
        while (len != -1) {
            digest.update(buffer, 0, buffer.size)
            len = inputStream.read(buffer, 0, buffer.size)
        }
        return toHex(digest.digest())
    }


    private fun toHex(byteArray: ByteArray): String {
        //转成16进制后是32字节
        return with(StringBuilder()) {
            byteArray.forEach {
                val hex = it.toInt() and (0xFF)
                val hexStr = Integer.toHexString(hex)
                if (hexStr.length == 1) {
                    append("0").append(hexStr)
                } else {
                    append(hexStr)
                }
            }
            toString()
        }
    }
}